<?php
// $Id$

/**
 * @file
 */

/**
 * Menu callback; Present an administrative event listing.
 */
function guild_admin_event_page() {
  $edit = $_POST;
  
  if (isset($edit['operation']) && ($edit['operation'] == 'delete') && isset($edit['events']) && $edit['events']) {
    module_load_include('inc', 'guild', 'includes/guild.admin');
    return drupal_get_form('guild_operation_multiple_delete_confirm');
  }
  
  return drupal_get_form('guild_event_overview');
}

/**
 * Form builder; Event editing page.
 *
 * @param array $form_state
 * @param string $op
 *   The editing operation, either 'add' or 'edit'.
 * @param array $event
 *   (optional) If supplied by the menu loader, contains an array with event values.
 *
 * @ingroup forms
 */
function guild_event_edit($form_state, $op, $event = NULL) {
  if (empty($event) || $op == 'add') {
    $event = array(
      'event_template_id' => NULL,
      'name' => '',
      'description' => '',
      'module' => 'guild',
      'type' => 'event'
    );
  }
  else {
    drupal_set_title(t('Event: @name', array('@name' => $event['name'])));
  }
  
  $form['event_op'] = array('#type' => 'value', '#value' => $op);
  $form['event_template_id'] = array('#type' => 'value', '#value' => $event['event_template_id']);
  $form['module'] = array('#type' => 'value', '#value' => $event['module']);
  $form['type'] = array('#type' => 'value', '#value' => $event['type']);
  
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Event name'),
    '#default_value' => $event['name'],
    '#maxlength' => 64,
    '#required' => TRUE
  );
  
  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Event description'),
    '#default_value' => $event['description'],
    '#rows' => 2
  );
  
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $op == 'edit' ? t('Update') : t('Create')
  );
  
  return $form;
}

/**
 * Validate an edited event form.
 */
function guild_event_edit_validate($form, &$form_state) {
  $event = $form_state['values'];
  
  // @todo Check comment length of event templates before submitting.
}

/**
 * Process and log an edited event form.
 */
function guild_event_edit_submit($form, &$form_state) {
  $values = $form_state['values'];
  $t_args = array('%name' => $values['name']);
  
  if ($values['event_op'] == 'add') {
    drupal_write_record('guild_event_template', $values);
    watchdog('guild', 'event: added template %name.', $t_args);
    
    drupal_set_message(t('The event %name has been created.', $t_args));
  }
  else {
    drupal_write_record('guild_event_template', $values, 'event_template_id');
    watchdog('guild', 'event: updated template %name.', $t_args);
    
    drupal_set_message(t('The event %name has been updated.', $t_args));
  }
  
  $form_state['redirect'] = 'admin/guild/events';
}

/**
 * Form builder;
 *
 * @see theme_guild_event_overview()
 */
function guild_event_overview(&$form_state) {
  module_load_include('inc', 'guild', 'includes/guild.admin');
  $form = guild_admin_operations('events');
  
  // Setup the table header.
  $form['header'] = array(
    '#type' => 'value',
    '#value' => array(
      theme('table_select_header_cell'),
      array('data' => t('Name'), 'field' => 'name', 'sort' => 'asc'),
      array('data' => t('Description'), 'field' => 'description'),
      array('data' => t('Last use')),
      array('data' => t('Operations'))
    )
  );
  
  // @todo Implement the "Last use" column of the event overview form.
  // @todo Apply the event name as a secondary sort order of the event overview form.
  
  $events_per_page = 50;
  $result = pager_query(
    "SELECT et.event_template_id AS id, et.name, et.description FROM {guild_event_template} et " .
    "WHERE et.module = '%s' AND et.type = '%s' " .
    tablesort_sql($form['header']['#value']), $events_per_page, 0, NULL, 'guild', 'event'
  );
  
  while ($event = db_fetch_object($result)) {
    $events[$event->id] = '';
    
    $form['name'][$event->id] = array('#value' => check_plain($event->name));
    $form['description'][$event->id] = array('#value' => check_plain(truncate_utf8($event->description, 40, TRUE, TRUE)));
    $form['lastuse'][$event->id] = array('#value' => '[NYI]');
    $form['operations'][$event->id] = array('#value' => l(t('edit'), 'admin/guild/events/' . $event->id . '/edit'));
  }
  
  $form['events'] = array('#type' => 'checkboxes', '#options' => isset($events) ? $events : array());
  $form['pager'] = array('#value' => theme('pager', NULL, $events_per_page, 0));
  
  return $form;
}

/**
 *
 *
 * @ingroup themeable
 */
function theme_guild_event_overview($form) {
  $output = drupal_render($form['update']);
  
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      $row = array();
      $row[] = drupal_render($form['events'][$key]);
      $row[] = drupal_render($form['name'][$key]);
      $row[] = drupal_render($form['description'][$key]);
      $row[] = drupal_render($form['lastuse'][$key]);
      $row[] = drupal_render($form['operations'][$key]);
      
      $rows[] = $row;
    }
  }
  else {
    $rows[] = array(array('data' => t('No events available.'), 'colspan' => '6'));
  }
  
  $output .= theme('table', $form['header']['#value'], $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}

/**
 * Helper function; Deletes an event from the database and logs any action.
 *
 * @see guild_delete_item(), guild_delete_raid()
 */
function guild_delete_event($event) {
  if (!is_object($event) || !is_numeric($event->event_template_id)) {
    watchdog('guild', 'Cannot delete a non-existant event.', array(), WATCHDOG_WARNING);
    return;
  }
  
  // Delete the event template.
  db_query('DELETE FROM {guild_event_template} WHERE event_template_id = %d', $event->event_template_id);
  watchdog('guild', 'event: deleted template %name.', array('%name' => $event->name));
  
  // @todo Notify other modules of a deleted event template.
  //guild_invoke_<your hook name>('delete', $event);
}

/**
 * Not used.
 */
function guild_event_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range(
      "SELECT et.event_template_id AS id, et.name FROM {guild_event_template} et " .
      "WHERE LOWER(et.name) LIKE LOWER('%%%s%%') AND et.type = '%s'",
      $string, 'event', 0, 10
    );
    
    while ($event = db_fetch_object($result)) {
      $matches[$event->name] = check_plain($event->name);
    }
  }
  
  drupal_json($matches);
}
